<script setup lang="ts">
/**
 * 保存/更新密码弹出按钮（地址栏内）
 */
import { computed, ref } from 'vue'
import { mdiShieldKey } from '@mdi/js'
import SavePass from './SavePass.vue'
import { useLayoutStore } from '@/windows/layoutBrowser/stores/layout'
import { createRuntimeState } from 'global-state'

const prop = defineProps<{ tab: F2.tab.Entity }>()
const layoutStore = useLayoutStore()

// 显隐状态：手动控制，避免因父级输入框行为导致默认点击未生效
const showPop = computed({
  get() {
    return layoutStore.showSavePasswordIds.has(prop.tab.id)
  },
  set(value) {
    if (value) {
      layoutStore.showSavePasswordIds.add(prop.tab.id)
    } else {
      layoutStore.showSavePasswordIds.delete(prop.tab.id)
    }
  }
})

function close(clear?: boolean) {
  showPop.value = false
  if (clear) passData.value = passData.value.filter(v => v.windowId !== prop.tab.webContentsId)
}

// 监听保存密码
const passData = ref<F2.user.WebCredential[]>([])
const currentPassData = computed(() =>
  passData.value.find(v => v.windowId === prop.tab?.webContentsId)
)
const passStore = createRuntimeState('passStore', {
  credentialId: '',
  domain: '',
  username: '',
  password: '',
  site_name: '',
  favicon_url: '',
  url: '',
  windowId: 0
})
passStore.watch((newVal, oldVal) => {
  const getKey = (v: F2.user.WebCredential) => [v.domain, v.username, v.password].join('_')
  if (newVal.domain && (!oldVal || getKey(newVal) !== getKey(oldVal))) {
    passData.value.push(newVal)
    if (newVal.windowId === prop.tab.webContentsId) showPop.value = true
  }
})
onBeforeUnmount(() => {
  passStore.destroy()
})
</script>

<template>
  <v-menu
    v-if="currentPassData"
    v-model="showPop"
    :close-on-content-click="false"
    location="bottom"
    :offset="6"
  >
    <template #activator="{ props }">
      <v-btn
        v-bind="props"
        class="cursor-pointer"
        color="primary"
        :icon="mdiShieldKey"
        @mousedown.stop
      />
    </template>
    <v-card>
      <SavePass :data="currentPassData" @cancel="close" />
    </v-card>
  </v-menu>
</template>

<style scoped></style>
